//
//  XLVideoPlayVC.m
//  XiangLove
//
//  Created by feng song on 2018/4/9.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLVideoPlayVC.h"
#import <BMHVideoPlayerView.h>
#import <BMHVideoConfig.h>
#import <BMHVideoPlayerControl.h>
 
#import "VideoRecordViewController.h"
#import "UIImage+Gradient.h"
#import "XLHTTPSessionManager+TaskLevel.h"
#import "XLVideoPushFinishView.h"

#import <AVFoundation/AVFoundation.h>
#import "SBCaptureDefine.h"
#import "XLPersonPageViewController.h"
#import "ZBMessageTextView.h"
#import "Sender.h"
#import "HelpTool.h"
#import "NSString+Ext.h"
#import "MBProgressHUD.h"
#import "ZYQAssetPickerController.h"
#import "SBCaptureToolKit.h"
#import "SFHFKeychainUtils.h"
#import "TXYUploadManager.h"
#import "UILabel+dynamicSize.h"
#define  SIGN_URL @"http://test.m.interface.baomihua.com/weise/WSVideoAction.ashx?action=sign&bucketName=bucket"

#define  ONE_SIGN_URL @"http://203.195.194.28/php/getsignv2.php?bucket=filename&service=cos&expired=0&path="

#import <MobileCoreServices/UTCoreTypes.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <MediaPlayer/MediaPlayer.h>
 
#import "XLHTTPSessionManager.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>
#import "XLMineViewController.h"
#import "XLAnchorCommitInforVC.h"

@interface XLVideoPlayVC ()<BMHVideoPlayerControllerDelegate>
{
    NSString *appId;
    NSString *bucket;
    NSString *persistenceId;
    NSString *videoPath;
    TXYVideoUploadTaskRsp *videoResp;
    TXYVideoUploadTask    *uploadVideoTask;
}

@property (nonatomic,strong) BMHVideoPlayerView *playerView;
@property (nonatomic,strong) TXYUploadManager   *uploadVideoManager;
@property (nonatomic,strong) TXYVideoUploadTask *uploadVideoTask;
@property (nonatomic,copy  ) NSString           *sign;
@property (nonatomic,copy  ) NSString           *fileName;

#define DECLARE_WEAK_SELF __typeof(&*self) __weak weakSelf = self
#define DECLARE_STRONG_SELF __typeof(&*self) __strong strongSelf = weakSelf
@end

@implementation XLVideoPlayVC


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.playerView play];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.playerView pause];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    [self initUpLodeVide];
    [self initPlay];
    
}

-(void)initUpLodeVide
{
    
    NSString *token = [[HelpTool getIOSuuid] substringToIndex:7];
    self.fileName = [NSString stringWithFormat:@"%@_%@", token, self.videoName];
    
    appId = @"10063237";//10063237
    bucket = @"dynamic"; //上传视频入口：发表动态：bucket=bucket 发红包视频：bucket=tempvideo
    
    persistenceId = @"videoID";//自定义,唯一,没有限制
    //上传视频总共五步之     第二步 向自己的业务服务器请求 上传image所需要的签名
    [self getUploadVidoSign];
    
    //上传视频总共五步之     第三步: 初始化上传工具
    _uploadVideoManager = [[TXYUploadManager alloc] initWithCloudType:TXYCloudTypeForVideo
                                                        persistenceId:persistenceId
                                                                appId:appId];
}

-(void)getUploadVidoSign
{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID, uid, publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    
    
    NSDictionary *cloundSignDic =[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",@"dynamic",@"BucketName",uid,@"UserID",locationString,@"Timestamp",nat,@"AppSign", nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/Video/VideoCloud.ashx" paraments:cloundSignDic success:^(id  _Nullable JSON) {
        NSLog(@"云存储签名==========-=-=-----%@", JSON);
        
        self.sign = JSON[@"result"][@"errmsg"];
        
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    
}

-(void)initPlay
{
    BMHVideoConfig *config = [[BMHVideoConfig alloc] init];
    self.playerView = [[BMHVideoPlayerView alloc] initWithFrame:self.view.frame delegate:self config:config];
    self.playerView.hidePlayControl = YES;
    self.playerView.coverView.contentMode = UIViewContentModeScaleAspectFill;
    self.playerView.coverView.image = _coverImage;
    [self.playerView.tx_player setRenderMode:RENDER_MODE_FILL_SCREEN];
    [self.view addSubview:self.playerView];
    [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self.playerView reloadContentUrl:_videoFileURL config:config];
    
    UIButton * returnShoot = [[UIButton alloc] init];
    [returnShoot setImage:[UIImage imageNamed:@"nav_but_fanhui_default"] forState:UIControlStateNormal];
    [returnShoot setTitle:@"重拍" forState:UIControlStateNormal];
    [returnShoot setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [returnShoot addTarget:self action:@selector(returnShootAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView addSubview:returnShoot];
    [returnShoot mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.playerView.mas_top).offset(31);
        make.left.equalTo(self.playerView.mas_left).offset(9);
    }];
    
    
    UIButton * commitVideo = [[UIButton alloc] init];
    [commitVideo setTitle:@"提交" forState:UIControlStateNormal];
    [commitVideo setTitleColor:kWhiteColor forState:UIControlStateNormal];
    commitVideo.layer.masksToBounds = YES;
    commitVideo.layer.cornerRadius = 25;
    [commitVideo setBackgroundColor:RGB_HEX(0xffbb001)];
    [commitVideo addTarget:self action:@selector(commitVideoAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView addSubview:commitVideo];
    [commitVideo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.playerView.mas_bottom).offset(-74);
        make.centerX.equalTo(self.playerView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(280, 50));
    }];
    
}

#pragma mark - BindAction
-(void)closeVideAciton:(UIButton *)closeVide
{
    if (self.selectedNavbar == YES) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else {
        UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UINavigationController *nav = [tabVC.viewControllers objectAtIndex:3];
        UIViewController *personVC;
        for (UIViewController *vc in nav.viewControllers) {
            if ([vc isKindOfClass:[XLMineViewController class]]) {
                personVC = vc;
                break;
            }
        }
        if (personVC) {
            [nav popToViewController:personVC animated:NO];
        } else {
            [nav popToRootViewControllerAnimated:NO];
        }
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    
    }
    
}

-(void)returnShootAction:(UIButton *)returnShoot
{
   
   if (self.selectedNavbar == YES) {
        UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UINavigationController *nav = [tabVC.viewControllers objectAtIndex:tabVC.viewControllers.count - 1];
        UIViewController *personVC;
        for (UIViewController *vc in nav.viewControllers) {
            if ([vc isKindOfClass:[VideoRecordViewController class]]) {
                personVC = vc;
                break;
            }
        }
        if (personVC) {
            [nav popToViewController:personVC animated:NO];
        } else {
            [nav popToRootViewControllerAnimated:NO];
        }
    
    }else {
        UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UINavigationController *nav = [tabVC.viewControllers objectAtIndex:tabVC.viewControllers.count - 1];
        UIViewController *personVC;
        for (UIViewController *vc in nav.viewControllers) {
            if ([vc isKindOfClass:[VideoRecordViewController class]]) {
                personVC = vc;
                break;
            }
        }
        if (personVC) {
            [nav popToViewController:personVC animated:NO];
        } else {
            [nav popToRootViewControllerAnimated:NO];
        }
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];

    }
    

    
}

-(void)commitVideoAction:(UIButton *)commitVide
{
    NSLog(@"提交视频");
    [self uploadVideoWihtVideoPath:self.videoFileURL];
}


#pragma mark - SDK Method
// 上传方法
-(void)uploadVideoWihtVideoPath:(NSString *)path
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    static int PAGE = 10;
    PAGE++;
    NSString * videTitleStr = [NSString stringWithFormat:@"%@%d",NSUser_object(UserID),PAGE];
    NSLog(@"=====path== %@",path);
    NSLog(@"=====videoPath==%@",videoPath);
    if(!self.sign){
        [self getUploadVidoSign];
    }
    TXYVideoFileInfo *videoFileInfo = [[TXYVideoFileInfo alloc]init];
    videoFileInfo.title = videTitleStr;
    videoFileInfo.desc = @"videodesc1";
    videoFileInfo.isCheck = 0;
    videoFileInfo.coverUrl= @"";//视频的自定义封面
    //上传视频总共四步之    第四步: 初始化上传化上传任务
    NSString *dir =[NSString stringWithFormat:@"/"];//[NSString stringWithFormat:@"/12",bucket];
    uploadVideoTask = [[TXYVideoUploadTask alloc] initWithPath:path
                                                          sign:_sign
                                                        bucket:bucket
                                                      fileName:self.fileName
                                               customAttribute:@"customAttribute"
                                               uploadDirectory:dir
                                                 videoFileInfo:videoFileInfo
                                                    msgContext:@"msgContext"
                                                    insertOnly:NO];
    //上传视频总共五步之   第五步: 上传任务
    DECLARE_WEAK_SELF;
    BOOL isSuccess = [_uploadVideoManager upload:uploadVideoTask
                                        complete:^(TXYTaskRsp *resp, NSDictionary *context) {
                                            DECLARE_STRONG_SELF;
                                            if (!strongSelf) return;
                                            videoResp = (TXYVideoUploadTaskRsp *)resp;
                                            NSLog(@"上传视频的url%@ 上传视频的fileid = %@",videoResp.fileURL,videoResp.fileId);
                                            NSLog(@"video is source url%@",videoResp.sourceURL);
                                            if ([videoResp.fileURL isEqualToString:@""] || videoResp.fileURL == nil) {

                                                [MBProgressHUD hideHUD];
                                                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                                [HelpTool startTipViewWithText:@"上传失败" duration:1 type:kTipViewTypeNone];
                                            }else {
                                                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                                [MBProgressHUD showContent:@"上传成功"];
                                                
                                                [self commitVideoUpData:videoResp.fileURL];
                                            }
                                            
                                        }
                                        progress:^(int64_t totalSize, int64_t sendSize, NSDictionary *context) {
                                            //命中妙传，不走这里的！
                                            NSLog(@" totalSize %lld",totalSize);
                                            NSLog(@" sendSize %lld",sendSize);
                                            NSLog(@" sendSize %@",context);
                                        }
                                     stateChange:^(TXYUploadTaskState state, NSDictionary *context) {
                                         switch (state) {
                                             case TXYUploadTaskStateWait:
                                                 NSLog(@"demoapp log 任务等待中");
                                                 break;
                                             case TXYUploadTaskStateConnecting:
                                                 NSLog(@"demoapp log 任务连接中");
                                                 break;
                                             case TXYUploadTaskStateFail:
                                                 [HelpTool startTipViewWithText:@"上传失败" duration:1 type:kTipViewTypeNone];
                                                 
                                                 [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                                 [MBProgressHUD hideHUD];
                                                 NSLog(@"demoapp log 任务失败");
                                                 break;
                                             case TXYUploadTaskStateSuccess:
                                                 NSLog(@"demoapp log 任务成功");
                                                 break;
                                             default:
                                                 break;
                                         }}];
    if (isSuccess == NO) {
        [MBProgressHUD hideHUD];[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [HelpTool startTipViewWithText:@"添加上传任务失败" duration:1 type:kTipViewTypeNone];
    }
}


-(void)commitVideoUpData:(NSString *)url
{
//    @weakify(self);
    NSDictionary *dict = @{@"key":url};
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"commitVideoUpData" object:nil userInfo:dict]];
    
//    UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//    UINavigationController *nav = [tabVC.viewControllers objectAtIndex:tabVC.selectedIndex];
    UIViewController *personVC = nil;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[XLAnchorCommitInforVC class]]) {
            personVC = vc;
            break;
        }
    }
    KPostNotification(KUPLOADVIDEOSUCCESSPOP, nil);
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    if (personVC) {
        [self.navigationController popToViewController:personVC animated:NO];
    } else {
        [self.navigationController popToRootViewControllerAnimated:NO];
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)removePlayerView {
    [self.playerView shutDownPlayer];
    [self.playerView removeFromSuperview];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
